package com.fkjslee.file;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author fkjslee
 * @date 2018/2/8 at 14:53
 * Copyright (c) 2018 fkjslee. All rights reserved.
 */

@Controller
public class FileController {
    //跳转到上传文件的页面
    @RequestMapping(value="/gouploading", method = RequestMethod.GET)
    public String goUploading() {
        //跳转到 templates 目录下的 uploading.html
        return "uploading";
    }

    //处理文件上传
    @RequestMapping(value="/testuploading", method = RequestMethod.POST)
    public @ResponseBody
    String uploading(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String filePath = "templates\\";
        try {
            uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "uploading success";
    }

    private void uploadFile(byte[] file, String filePath, String fileName){
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(filePath + fileName);
            out.write(file);
            out.flush();
            out.close();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}
